package com.firefighting.maintenancer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.firefighting.util.JdbcUtils;
import com.firefighting.util.MYJSONObject;

/**
 * Servlet implementation class TaskMaintenancerPhoto
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/TaskMaintenancerPhoto" })
public class TaskMaintenancerPhoto extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		System.out.println("-----"+format.format(new Date())+"    "+this.getServletName()+"-----");
		/*System.out.println("---------url传参----------");
		String userId=request.getParameter("userId");
		String task_id = request.getParameter("task_id");
		String photo=request.getParameter("photo");
		System.out.println("userId="+userId);
		System.out.println("task_id="+task_id);
		System.out.println("photo="+photo);
		System.out.println("---------url传参结束------");*/
		String userId = null;
		String task_id = null;
		
		//String savePath = this.getServletContext().getRealPath("/cache_files");
		String savePath = "http://47.106.213.57:8080/image/maintenancer";
		String saveFile = null;
		File test_file = new File(savePath);
		if (!test_file.exists()) {
			test_file.mkdirs();
		}
		System.out.println("savePath="+savePath);

		PrintWriter out = response.getWriter();
		MYJSONObject result_jb = new MYJSONObject();
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String image_url = "";
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			if (!ServletFileUpload.isMultipartContent(request)) {
				result_jb.put("status", "false");
				result_jb.put("message", "普通表单");
				System.out.println("普通表单");
				return;
			}
			List<FileItem> list = upload.parseRequest(request);

			for (FileItem item : list) {
				if (item.isFormField()) {
					System.out.println("非文件数据项");
					String field_name = item.getFieldName();
                    //解决普通输入项的数据的中文乱码问题
                    String value = item.getString("UTF-8");

            		System.out.println("---------表单传参----------");
            		System.out.println("field_name="+field_name);
            		System.out.println("value="+value);
            		System.out.println("---------表单传参结束------");
                    switch (field_name) {
						case "userId":
							userId = value;
							break;
						case "task_id":
							task_id = value;
							break;
						default:
							break;
					}
				} else {
					System.out.println("item.getSize="+item.getSize());
					if (item.getSize() > (1024 * 1024 * 100)) {
						result_jb.put("status", "false");
						result_jb.put("message", "上传文件超过100M");
						System.out.println("上传文件超过100M");
						return;
					}
					String filename = item.getName();
					System.out.println("filename="+filename);
					if (filename == null || "".equals(filename.trim())) {
						result_jb.put("status", "false");
						result_jb.put("message", "上传文件的文件名为空");
						System.out.println("上传文件的文件名为空");
						return;
					}
					//fileExtName为扩展名
					String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
					System.out.println("fileExtName="+fileExtName);
					if (!"jpg".equals(fileExtName)
							&& !"JPG".equals(fileExtName)
							&& !"jpeg".equals(fileExtName)
							&& !"JPEG".equals(fileExtName)
							&& !"png".equals(fileExtName)
							&& !"PNG".equals(fileExtName)) {

						result_jb.put("status", "false");
						result_jb.put("message", "上传文件格式不正确");
						System.out.println("上传文件格式不正确");
						return;
					}
					InputStream in = item.getInputStream();
					format = new SimpleDateFormat("yyyyMMddHHmmss");
					String time = format.format(new Date());
					String current_time = String.valueOf(System.currentTimeMillis());
					String rand = current_time.substring(current_time.length()-2, current_time.length());
					String saveFilename = "maintenancer_" + userId+"_"+time + rand + "." + fileExtName;
					System.out.println("saveFilename="+saveFilename);
					saveFile = savePath + "/" + saveFilename;
					System.out.println("saveFile="+saveFile);
					FileOutputStream outputStream = new FileOutputStream(saveFile);
					byte buffer[] = new byte[1024];
					int len = 0;
					while ((len = in.read(buffer)) > 0) {
						outputStream.write(buffer, 0, len);
					}
					in.close();
					outputStream.close();

					System.out.println("文件上传成功");
					/*image_url += request.getScheme() + "://" + request.getServerName() + ":" +request.getServerPort()+ request.getContextPath() 
						+ "/cache_files/"+saveFilename +";";*/
					image_url += savePath+"/"+saveFilename +";";
					System.out.println("image_url="+image_url);

				}
			}

			System.out.println("userId="+userId);
			System.out.println("task_id="+task_id);
			image_url = image_url.substring(0, image_url.length()-1);
			System.out.println("image_url="+image_url);
			
			connection = JdbcUtils.getConnection();
			String sql ="update task set task.maintenancer_photo=?  where task.id=? and task.app_id_account=? ";
			ps = connection.prepareStatement(sql);
			ps.setString(1, image_url);
			ps.setString(2, task_id);
			ps.setString(3, userId);
			
			if (ps.executeUpdate() > 0) {
				result_jb.put("status", "true");
				result_jb.put("message", "任务对应的维保工程师照片上传成功");
				System.out.println("任务对应的维保工程师照片上传成功");
			}
			else {
				result_jb.put("status", "false");
				result_jb.put("message", "任务对应的维保工程师照片上传失败");
				System.out.println("任务对应的维保工程师照片上传失败");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			result_jb.put("status", "false");
			result_jb.put("message", "服务器异常");
			System.out.println("服务器异常");
		} finally {
			JdbcUtils.free(rs, ps, connection);
			out.print(result_jb.toString());
			out.flush();
			out.close();
		}
	}

}
